package com.apache.tools;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URL;
import java.util.Map;

import org.apache.log4j.Logger;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class TemplateUtil {
	private static final Logger logger = Logger.getLogger(TemplateUtil.class);
	private static String charset = "UTF-8";

	/**
	 * 初始化模板文件
	 * @param templateFilePath 模板文件夹路径
	 * @return
	 */
	private static Configuration getFreeMarkerCFG(String templateFilePath) throws Exception {
		Configuration freemarker_cfg = new Configuration();
		freemarker_cfg.setDefaultEncoding(charset);
		freemarker_cfg.setDirectoryForTemplateLoading(new File(templateFilePath));
		return freemarker_cfg;
	}

	/**
	 * 读取模版数据 （注意模版路径=/WEB-INF/classes/template/）
	 * @param tempateName 模版名称
	 * @param map 模版需要的数据
	 * @return 模版内容，为空表示异常
	 */
	public static String getTempateContent(String tempateName, Map<String, Object> map) {
		try {
			String emailTempatePath = "/WEB-INF/classes/template/";
			String ctx = getClassLoaderPath() + "template/";
			Configuration configuration = getFreeMarkerCFG(ctx + emailTempatePath);
			if (configuration != null) {
				Template template = configuration.getTemplate(tempateName, charset);
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				StringBuffer sbuff = new StringBuffer();
				Writer out = new OutputStreamWriter(bos, charset);
				template.process(map, out);
				sbuff.append(new String(bos.toByteArray(), charset));
				String content = sbuff.toString();
				out.close();
				return content;
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			logger.error(tempateName + "模版读取失败！！" + e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			logger.error(tempateName + "模版读取失败！！" + e.getMessage());
		} catch (TemplateException e) {
			e.printStackTrace();
			logger.error(tempateName + "模版读取失败！！" + e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(tempateName + "模版读取失败！！" + e.getMessage());
		}
		return null;
	}

	public static String getClassLoaderPath() {
		String path = "";
		URL classLoaderUrl = Thread.currentThread().getContextClassLoader().getResource("");
		if (null == classLoaderUrl) {
			path = Thread.currentThread().getContextClassLoader().getResource("/").getPath();//tomcat/weblogic
		} else {
			path = classLoaderUrl.getPath();
		}
		if (StrUtil.isNotNull(path)) {
			if (path.startsWith(File.separator) || path.startsWith("/")) {
				String systemType = getSystemType();
				if ("windows".equals(systemType))
					path = path.substring(1);
			}
			if (!path.endsWith(File.separator) && !path.endsWith("/"))
				path += "/";
		}
		return path;
	}

	/**
	 * 获取操作系统类型
	 *
	 * @return 返回操作系统类型
	 */
	public static String getSystemType() {
		String result = "windows";
		if (System.getProperty("os.name").equals("Linux")) {
			result = "linux";
		} else if ("Mac OS X".equals(System.getProperty("os.name"))) {
			result = "Mac OS X";
		}
		return result;
	}
}
